package com.maven.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ComsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 建立连接： 首先 弄一个建立连接的 工厂，将 必要信息进行设置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("8.135.54.49");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("study");
        connectionFactory.setPassword("study");
        connectionFactory.setVirtualHost("rabbitmq");

        // 2. 从 工厂中取出一个连接
        Connection connection = connectionFactory.newConnection();
        // 3. 建立信道
        Channel channel = connection.createChannel();
        // 4. 声明队列
        channel.queueDeclare("produced",true,false,true,null);


        // 5. 消费 信息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("收到信息：" + new String(body));
            }
        };
        channel.basicConsume("produced",true,consumer);

        channel.close();
        connection.close();
    }
}
